const { Server } = require("socket.io");

module.exports = (server) => {
  console.log("你好");
  const io = new Server(server, {
    cors: true,
  });
  const userlist = new Map();
  io.on("connection", (socket) => {
    console.log("收到用户端请求");
    console.log(socket.id);
    let second = 0;
    setInterval(() => {
      second++;
    }, 1000);
    // socket.on("disconnect", (reason) => {
    //   console.log("总共耗时" + second);
    //   console.log("断开链接", reason);
    // });
    socket.on("sendmsg", (msg, callback) => {
      console.log(msg);
      // 回调函数
      // callback(msg);
      socket.emit("chatmsg", {
        status: 200,
        data: "result",
      });
      socket.broadcast.emit("broadcastmsg", msg);
    });

    socket.on("msg", (msg) => {
      console.log(msg);
    });
    // Map{userid:socketid} 唯一性
    socket.on("registerUserid", (userid) => {
      userlist.set(userid, socket.id);
      console.log("当前在线用户:", userlist);
      socket.broadcast.emit("loginSuccess", "有人加入了链接");
      // 用户退出
      socket.on("disconnect", (res) => {
        userlist.delete(userid)
        console.log(userid+"用户退出,原因",res);
        console.log("当前在线用户:", userlist); 
      });
    }); 

    // 接受用户发送消息，包括id发给谁 
    socket.on("privateMsg",({toId,fromId,msg})=>{ 
      userlist.get(toId)&&socket.to(userlist.get(toId)).emit("receivePrivateMsg",({...msg,fromId}))
      userlist.get(toId)&&socket.to(userlist.get(toId)).emit("updateMessageList",(fromId))
    })
  });
};
